import { getDict } from '../../../api/config';

export const useApi = (apiConfigs, emits) => {
  /**
   * @description: 获取字典项的ajax
   * @param: dictData<Array> 字典数组
   * @param: list<Array> 表单的configs
   * @return: 有一个onCreated 的方法 用于给字典项默认值
   */
  const getDictData = async (dictData, list) => {
    const formItemList = list.reduce((pre, cur) => {
      pre = pre.concat(cur.list);
      return pre;
    }, []);
    const dictList = formItemList.filter(item => item && item.dictCode).map(item => item.dictCode);
    if (dictList.length === 0) return [];
    if (!apiConfigs.dictUrl) return;
    const ret = await getDict(apiConfigs.dictUrl, { keys: dictList });
    dictData.value = ret;
    emits('onCreated', ret);
  };

  return {
    getDictData,
  };
};
